package jnpf.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.base.service.IBaseSerialNumberService;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.fico.entity.ZcBillEntity;
import jnpf.fico.entity.ZcBillItemEntity;
import jnpf.fico.mapper.ZcBillItemMapper;
import jnpf.fico.mapper.ZcBillMapper;
import jnpf.htgl.entity.ZcglHtglInfoEntity;
import jnpf.htgl.entity.ZcglHtglPabEntity;
import jnpf.htgl.entity.ZcglHtglSkjhEntity;
import jnpf.htgl.entity.ZcglHtglSkjhHistoryEntity;
import jnpf.htgl.mapper.ZcglHtglInfoMapper;
import jnpf.htgl.mapper.ZcglHtglPabMapper;
import jnpf.htgl.mapper.ZcglHtglSkjhHistoryMapper;
import jnpf.htgl.mapper.ZcglHtglSkjhMapper;
import jnpf.util.GeneraterSwapUtil;
import jnpf.util.RandomUtil;
import jnpf.zc.entity.ZcglCustomerEntity;
import jnpf.zc.entity.ZcglCustomerUserEntity;
import jnpf.zc.mapper.ZcglCustomerMapper;
import jnpf.zc.mapper.ZcglCustomerUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @description: 定时任务实体类
 * @author: zhengxiong.jiang
 * @createDate: 2025-01-22
 * @version: 1.0
 */
@Component
public class ScheduledTask {

    @Autowired
    private ZcglHtglSkjhMapper zcglHtglSkjhMapper;
    @Autowired
    private ZcBillMapper zcBillMapper;
    @Autowired
    private ZcglHtglPabMapper zcglHtglPabMapper;
    @Autowired
    private IBaseSerialNumberService iBaseSerialNumberService;
    @Autowired
    private ZcglHtglInfoMapper zcglHtglInfoMapper;
    @Autowired
    private ZcBillItemMapper zcBillItemMapper;
    @Autowired
    private ZcglHtglSkjhHistoryMapper zcglHtglSkjhHistoryMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private ZcglCustomerMapper zcglCustomerMapper;
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Async
    @Scheduled(fixedRate = 60000) //每隔10分钟（600000ms）
    public void performTask() {
        System.out.println("Scheduled task started");

        // 使用事务模板管理异步事务
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.execute(status -> {
            try {
                // 执行数据库操作或事务相关操作
                processTaskWithTransaction();
            } catch (Exception e) {
                status.setRollbackOnly();  // 手动回滚事务
                throw e;
            }
            return null;
        });

        System.out.println("Scheduled task finished");
    }

    // 事务操作方法
    public void processTaskWithTransaction() {
        System.out.println("Processing task in thread: " + Thread.currentThread().getName());
        // 执行事务逻辑，例如数据库操作
        List<ZcglHtglSkjhEntity> zcglHtglSkjhEntities = zcglHtglSkjhMapper.selectList(new QueryWrapper<ZcglHtglSkjhEntity>());

        if(IterUtil.isNotEmpty(zcglHtglSkjhEntities)){
            zcglHtglSkjhEntities.stream().forEach(i->{

                //如果当前时间大于等于收款日期，那么开始生成账单
                Date today = DateUtil.parse(DateUtil.today());
                Date paymentDate = DateUtil.parse(i.getPaymentDate());
                if(DateUtil.today().equals(i.getPaymentDate()) || today.after(paymentDate)){
                    //账单生成
                    ZcBillEntity zcBillEntity = new ZcBillEntity();
                    String parentid = i.getParentid();
                    ZcglHtglInfoEntity zcglHtglInfoEntity = zcglHtglInfoMapper.selectById(parentid);
                    //如果是驳回状态就不生成账单数据
                    FlowTaskEntity flowTaskEntity = generaterSwapUtil.getInfoSubmit(zcglHtglInfoEntity.getId(), FlowTaskEntity::getStatus);
                    System.out.println(flowTaskEntity.getStatus()+"看看状态");
                    if(flowTaskEntity!=null &&flowTaskEntity.getStatus()==2){
                        ZcglHtglPabEntity zcglHtglPabEntity = zcglHtglPabMapper.selectOne(new QueryWrapper<ZcglHtglPabEntity>()
                                .eq("F_PARENTID", parentid)
                        );
//                        ZcglCustomerEntity zcglCustomerEntity = zcglCustomerMapper.selectById(zcglHtglPabEntity.getPabCustomerName());
//                        zcBillEntity.setCustomerName(zcglCustomerEntity.getCustomerName());
                        zcBillEntity.setCustomerName(zcglHtglPabEntity.getPabCustomerName());

                        zcBillEntity.setBillNo(iBaseSerialNumberService.getSerialNumber("ZD",8));
                        zcBillEntity.setContractNo(zcglHtglInfoEntity.getContractNumber());
                        zcBillEntity.setLeaseSpace(i.getRelatedSpace());
                        String[] qjDate = i.getIntervall().split("至");
                        zcBillEntity.setExpenseStartDate(DateUtil.parseDate(qjDate[0]));
                        zcBillEntity.setExpenseEndDate(DateUtil.parseDate(qjDate[1]));
                        String mainId = RandomUtil.uuId();
                        zcBillEntity.setId(mainId);
                        zcBillEntity.setCreatortime(new Date());
                        zcBillMapper.insert(zcBillEntity);

                        //具体费用项生成
                        ZcBillItemEntity zcBillItemEntity = new ZcBillItemEntity();
                        zcBillItemEntity.setParentid(mainId);
                        zcBillItemEntity.setId(RandomUtil.uuId());
                        zcBillItemEntity.setExpenseItem(i.getExpenseItem());
                        zcBillItemEntity.setStatus(ZcBillItemEntity.STATUS_1);
                        zcBillItemEntity.setPendAmount(BigDecimal.valueOf(Double.valueOf(i.getInclusiveAmount())));
                        zcBillItemEntity.setReceivedAmount(BigDecimal.valueOf(0));
                        zcBillItemEntity.setRealAmount(BigDecimal.valueOf(Double.valueOf(i.getInclusiveAmount())));
                        zcBillItemEntity.setReceiveAmount(BigDecimal.valueOf(Double.valueOf(i.getInclusiveAmount())));
                        zcBillItemEntity.setCreatortime(new Date());
                        zcBillItemMapper.insert(zcBillItemEntity);

                        //当账单逻辑生成之后生成收款计划历史数据用于追溯
                        zcglHtglSkjhMapper.deleteById(i.getId());
                        ZcglHtglSkjhHistoryEntity zcglHtglSkjhHistoryEntity = new ZcglHtglSkjhHistoryEntity();
                        BeanUtil.copyProperties(i,zcglHtglSkjhHistoryEntity);
                        zcglHtglSkjhHistoryMapper.insert(zcglHtglSkjhHistoryEntity);
                    }
                }

            });
        }
    }

}
